package service;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import common.kit.DateKits;
import common.kit.PageSql;
import model.GasReplace;
import model.Staff;

public class GasReplaceService extends BaseService {

	public Ret save(GasReplace gasReplace , Staff staff , Long stationId) {
		gasReplace.setStationId(stationId);
		gasReplace.setRecorder(staff.getName());
		gasReplace.setServierId(staff.getServicerId());
		gasReplace.save();
	    return ok() ;
	}

	public Page<Record> getApiPage(Kv kv , Integer pageNumber , Integer pageSize) {
		String select = " tgr.id,tgr.createTime,tgr.recorder,tgr.name,tgr.gasConcentration,tgr.unit,tgr.count,tgr.deadline,ts.name AS servicerName " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_gas_replace tgr ") ;
	    pageSql.join(" t_servicer ts " , " ts.id = tgr.servierId ") ;
		pageSql.setEqualCondition("tgr.stationId") ; //点位	 
		pageSql.setNotLessThanCondition("tgr.deadline","tgr.deadline.start") ; //有效期
		pageSql.setNotMoreThanCondition("tgr.deadline","tgr.deadline.end") ; //有效期
		pageSql.setNotLessThanCondition("tgr.createTime", "startTime");
		pageSql.setNotMoreThanCondition("tgr.createTime", "endTime");
	    pageSql.orderBy(" tgr.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		List<Record> list = page.getList();
		for (Record record : list) {
			record.set("isDued", record.getDate("deadline").getTime() <= System.currentTimeMillis());
			record.set("deadline", DateKits.toStr(record.getDate("deadline")));
		}
		return page ;
	}

	public Page<Record> getPage(Kv kv , Integer pageNumber , Integer pageSize) {
		String select = " tgr.id,tgr.createTime,tgr.name,tgr.gasConcentration,tgr.unit,tgr.count,tgr.deadline,ts.name AS stationName,tc.name AS companyName2,tsr.name AS servicerName1,tgr.recorder " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_gas_replace tgr ") ;
	    pageSql.join(" t_station ts " , " ts.id = tgr.stationId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tgr.servierId ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
		pageSql.setNotLessThanCondition("tgr.createTime","tgr.createTime.start") ; //创建时间
		pageSql.setNotMoreThanCondition("tgr.createTime","tgr.createTime.end") ; //创建时间
		pageSql.setEqualCondition("tgr.stationId") ; //点位	 
		pageSql.setNotLessThanCondition("tgr.deadline","tgr.deadline.start") ; //有效期
		pageSql.setNotMoreThanCondition("tgr.deadline","tgr.deadline.end") ; //有效期
		pageSql.setLikeCondition("ts.name") ; //点位名称	 
		pageSql.setLikeCondition("tsr.name") ; //运维公司	 
		pageSql.setLikeCondition("tc.name") ; //企业名称	 
	    pageSql.orderBy(" tgr.createTime DESC ");
		return pageSql.paginate( pageNumber , pageSize) ;
	}
}
